//
//  SEGWKWebViewLoadController.m
//  SEGStandard
//
//  Created by 山刘 on 2020/3/16.
//

#import "SEGWKWebViewLoadController.h"
#import "SEGReadFileViewController.h"
#import "WKProcessPool+SharedProcessPool.h"
#import "SEGNaviHeaderView.h"

#import "SEGDocument.h"
#if __has_include(<Commom/SEGAlertView.h>)
#import <Commom/SEGAlertView.h>
#else
#import "SEGAlertView.h"
#endif

#if __has_include(<Commom/SEGUploadmultipartfileManager.h>)
#import <Commom/SEGUploadmultipartfileManager.h>
#else
#import "SEGUploadmultipartfileManager.h"
#endif

#if __has_include(<Commom/SEGLayoutMacro.h>)
#import <Commom/SEGLayoutMacro.h>
#else
#import "SEGLayoutMacro.h"
#endif

#if __has_include(<Commom/SEGMultipartfileuploadManager.h>)
#import <Commom/SEGMultipartfileuploadManager.h>
#else
#import "SEGMultipartfileuploadManager.h"
#endif

#if __has_include(<Commom/SEGColorManager.h>)
#import <Commom/SEGColorManager.h>
#else
#import "SEGColorManager.h"
#endif

#if __has_include(<CommonMediator/SEGMediatorHeader.h>)
#import <CommonMediator/SEGMediatorHeader.h>
#else
#import "SEGMediatorHeader.h"
#endif

#import "SEGWebViewLoadManager.h"
#import "SEGUrlparamsModel.h"
#import "SEGSystemnativeModel.h"

#import "SEGNaviHeaderView.h"

#import <Masonry/Masonry.h>

#if __has_include(<Commom/SEGPlatformManager.h>)
#import <Commom/SEGPlatformManager.h>
#else
#import "SEGPlatformManager.h"
#endif

#if __has_include(<commonThirds/SEGImagePickerManager.h>)
#import <commonThirds/SEGImagePickerManager.h>
#else
#import "SEGImagePickerManager.h"
#endif

#import <MessageUI/MessageUI.h>

static id _webViewLoadController;
static dispatch_once_t onceToken;

static NSString* kvo_URL = @"URL"; //WKWebView的URL属性，监控URL变化
static NSString* kvo_estimatedProgress = @"estimatedProgress";//WKWebView的estimatedProgress属性，监控estimatedProgress变化，设置加载进度条
static NSString* kvo_title = @"title";
static NSString* kvo_canGoBack = @"canGoBack";

static NSString* UserDefaultEnumNavigationBarShowTypeKey = @"UserDefaultEnumNavigationBarShowTypeKey";
typedef NS_ENUM(NSUInteger, SEGEnumNavigationBarShowType) {
    SEGEnumNavigationBarShowType_NO = 1, /*都不展示*/
    SEGEnumNavigationBarShowType_System = 0, /*展示系统*/
    SEGEnumNavigationBarShowType_Custom = 2, /*展示自定义 圆角返回按钮*/
    SEGEnumNavigationBarShowType_NONav = 3  /*没有导航，没有状态栏*/
};

@interface SEGWKWebViewLoadController ()<UIActionSheetDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate,SEGSEGNaviHeaderViewProtocol,SEGNaviHeaderScrollViewProtocol, UIDocumentMenuDelegate ,UIDocumentPickerDelegate,SEGImagePickerManagerDelegate,MFMessageComposeViewControllerDelegate>

/**
 导航栏视图,存放在导航栏中
 */
@property (nonatomic, strong)SEGNaviHeaderView *headerView;

/**
 导航栏隐藏后的导航栏视图
 */
@property (nonatomic, strong)SEGNaviHeaderView *naviHideHeaderView;
@property (nonatomic, assign) NSInteger headerViewTag;
/**
 当前正在活动状态的URL地址
 */
//@property (nonatomic, copy) NSURL *currentUrl;

/**
 获取当前页面的地址，针对带#的URL链接。
 */
//@property (nonatomic, copy) NSString *documentURL;

/**
 网页进度条
 */

/**
 通过url参数(isHideHeader)判断网页加载导航栏显示和隐藏情况：1:隐藏系统导航栏，其他：显示
 */
/**
 判断是否是无纸化协议
 */

/**
 判断支付类型
 */
@property (nonatomic, assign) SEGPayTypeName payType;

/// 状态栏背景颜色
@property (nonatomic, strong) UIView *statusBarBackView;
// 记录上次的URL HOST 用于微信H5支付
@property (nonatomic, copy) NSString *hostString;

@property (nonatomic, strong) SEGImagePickerManager *imagePicker;

/**
 是否展示分享按钮
 */
@property (nonatomic, assign) BOOL hasShareBtn;
@end

@implementation SEGWKWebViewLoadController{
    //设置最大图片数
    NSInteger maxPhoto;
    NSString *qch_backUrl;
}

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.hasShareBtn = NO;
    self.view.backgroundColor = UIColor.whiteColor;
    [self setNavigationShow:SEGEnumNavigationBarShowType_System hasShare:self.hasShareBtn];
    maxPhoto = 1;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (@available(iOS 11.0, *)) {
        self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        self.edgesForExtendedLayout = UIRectEdgeAll;
    }
    
    if (!(self.headerView.title && self.headerView.title.length > 0)) {
        self.headerView.title = self.title;
    }
    
    if (self.isHideHeader) {
        [self setNavigationShow:SEGEnumNavigationBarShowType_NO hasShare:NO];
        self.isHideHeader = NO;
    }else if (self.isDigitalComunity) { // 数字社区不展示导航栏
        [self setNavigationShow:SEGEnumNavigationBarShowType_Custom hasShare:NO];
    }else if (self.isRootVC) {
        [self setNavigationShow:SEGEnumNavigationBarShowType_NONav hasShare:NO];
    }else{
        SEGEnumNavigationBarShowType type = self.hasShareBtn ? SEGEnumNavigationBarShowType_Custom : (SEGEnumNavigationBarShowType)[[[NSUserDefaults standardUserDefaults]objectForKey:UserDefaultEnumNavigationBarShowTypeKey] integerValue];
        [self setNavigationShow:type hasShare:self.hasShareBtn];
    }
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self setStatusBarBackgroundColor:[UIColor clearColor]];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}

#pragma mark - 实现父类抽象方法
/// 添加子视图
-(void)segAddSubview{
    [super segAddSubview];
    
    [self initNaviHeaderView];
    [self.view addSubview:self.naviHideHeaderView];
    [self.view addSubview:self.progressView];
    
    [self.naviHideHeaderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(LYStatusBarHeight());
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(kNavigationBarHeight);
    }];
    
    //UIProgressView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, 2)];
    [self.progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(0);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(2);
    }];
    
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
    
    self.headerView.title = self.title;
}

/// 添加监听KVO
-(void)segAddKVO{
    [super segAddKVO];
}

/// 添加通知
-(void)segAddNotifications{
    [super segAddNotifications];
}

/// JS协议拦截
/// @param webView webView
/// @param request request
/// @param query query 经过了逻辑处理后的query
-(BOOL)jsInvokeSystemFunctionWithWebView:(WKWebView *)webView request:(NSURLRequest *)request query:(NSString *)query{
    NSString * scheme = request.URL.scheme;
    NSString * host = request.URL.host;
    
    //遇到特殊文件的跳转逻辑:
    if ([@[@"pdf",@"txt",@"doc",@"docx",@"xlsx",@"txt"] containsObject:request.URL.pathExtension]) {
        SEGReadFileViewController *VC = [SEGReadFileViewController new];
        VC.linkURL  = request.URL.absoluteString;
        [self.navigationController pushViewController:VC animated:YES];
        return NO;
    }
    
    // 基于：window.location.href拦截JS协议，唤起原生方法
    if (scheme && host && [scheme rangeOfString:@"uhomeoc"].location != NSNotFound){
        if ([host rangeOfString:@"business.openActDetail"].location != NSNotFound){ // 商业改造-打开商品详情
            [self segJSBusinessOpenActDetailWithQuery:query request:request.URL];
            return NO;
        }
        if ([host rangeOfString:@"homeservice.setHeadTitle"].location != NSNotFound){ // 到家服务-设置标题栏标题，选中状态
            [webView evaluateJavaScript:[self segJSHomeserviceSetHeadTitleWithQuery:query] completionHandler:^(id _Nullable req, NSError * _Nullable error) {
            }];
            
            return NO;
        }
        if ([host rangeOfString:@"homeservice.setSharePara"].location != NSNotFound){ // 设置分享参数
            [self segJSHomeserviceSetShareParaWithQuery:query];
            
            return NO;
        }
        if ([host rangeOfString:@"homeservice.counseling"].location != NSNotFound){ // 客服跳转
            [self segJSHomeserviceCounselingWithQuery:query request:request.URL];
            
            return NO;
        }
        if ([host rangeOfString:@"homeservice.confirmOrder"].location != NSNotFound){ // 确认订单页跳转
            [self segJSHomeserviceConfirmOrderWithQuery:query request:request.URL];
            
            return NO;
        }
        if ([host rangeOfString:@"userInfo.get"].location != NSNotFound) { // 用户信息-获取用户信息
            [webView evaluateJavaScript:[self segJSUserInfoGetWithQuery:query] completionHandler:^(id _Nullable req, NSError * _Nullable error) {
                
            }];
            return NO;
        }
        if ([host rangeOfString:@"system.openImgViewer"].location != NSNotFound) { // 使用原生系统功能：使用系统自带图片浏览器打开图片
            [self segJSSystemOpenImgViewerWithQuery:query];
            
            return NO;
        }
        if ([host rangeOfString:@"system.addToClipboard"].location != NSNotFound) { // 使用原生系统功能：把字符串添加到系统剪贴板
            [self segJSSystemAddToClipboardWithQuery:query];
            
            return NO;
        }
        if ([host rangeOfString:@"system.jumpToNative"].location != NSNotFound) { // 使用原生系统功能：跳转到原生页面
            [self segJSSystemJumpToNativeWithQuery:query request:request.URL];
            
            return NO;
        }
        if ([host rangeOfString:@"system.uploadFiles"].location != NSNotFound) { // 使用原生系统功能：批量上传文件
            [self segJSSystemUploadFilesWithQuery:query request:request.URL];
            
            return NO;
        }
        if ([host rangeOfString:@"system.hideHeader"].location != NSNotFound) { // 使用原生系统功能：隐藏原生头部导航栏
            [self segJSSystemHideHeaderWithQuery:@""];
            
            return NO;
        }
        if ([host rangeOfString:@"system.socialShare"].location != NSNotFound) { // 使用原生系统功能：分享到社交平台
            
            [self segJSSystemSocialShareWithQuery:query request:request.URL];
            
            return NO;
        }
        if ([host rangeOfString:@"thirdparty.takePhoto"].location != NSNotFound) { // 第三方使用api：拍照
            [self segJSThirdpartyTakePhotoWithQuery:query];
            
            return NO;
        }
        if ([host rangeOfString:@"system.camera"].location != NSNotFound) { // 使用原生系统功能：相机
            [self segJSSystemCameraWithQuery:query request:request.URL];
            
            return NO;
        }
        if ([host rangeOfString:@"thirdparty.goBack"].location != NSNotFound) { // 第三方使用api：返回native界面
            [self segJSThirdpartyGoBackWithQuery:query];
            
            return NO;
        }
        if ([host rangeOfString:@"thirdparty.openDialog"].location != NSNotFound) { // 第三方使用api：弹出确认框
            [self segJSThirdpartyOpenDialogWithQuery:query];
            
            return NO;
        }
        if ([host rangeOfString:@"thirdparty.goPayList"].location != NSNotFound) { // 第三方使用api：跳转到支付列表
            [self segJSThirdpartyGoPayListWithQuery:query request:request.URL];
            
            return NO;
        }
        if ([host rangeOfString:@"thirdparty.pay"].location != NSNotFound) { // 第三方使用api：支付
            [self segJSThirdpartyPayWithQuery:query request:request.URL];
            
            return NO;
        }
        if ([host rangeOfString:@"system.takeFiles"].location != NSNotFound) { // 使用原生系统功能：批量获取本地文件
            [self segJSSystemTakeFilesWithQuery:query request:request.URL];
            
            return NO;
        }
        if (([host rangeOfString:@"system.getCookie"].location != NSNotFound)||[host rangeOfString:@"system.getSysCookie"].location != NSNotFound) { // 获取cookie
            [self seg_getCookieWithURL:request.URL.absoluteString];
            
            return NO;
        }
        if ([host rangeOfString:@"system.signature"].location != NSNotFound) { // 使用原生系统功能：签名
            @weakify(self)
            UIViewController *VC =  [[SEGUhomeMediator sharedInstance] seg_initSEGSignViewController:^(UIImage * image) {
                @strongify(self)
                [self segJSSystemSignatureWithQuery:query request:request.URL image:image];
            }];
            [self.navigationController pushViewController:VC animated:YES];
            
            return NO;
        }
        if ([host rangeOfString:@"system.logout"].location != NSNotFound) { // 使用原生系统功能：退出登录
            [[SEGHTTPManager sharedNetworkManager]removeCookies];//登录前清除cookies
            [[SEGHTTPManager sharedNetworkManager] segCancelAllRequest];
            [[SEGUhomeMediator sharedInstance]seg_pushToLoginViewController:nil];
            
            return NO;
        }
        if ([host rangeOfString:@"thirdparty.openWXMiniProgram"].location != NSNotFound) { //  第三方使用api：打开小程序
            [self segJSThirdpartyMiniProgramWithQuery:query];
            
            return NO;
        }
    }
    
    // iOS接入微信H5支付
    NSDictionary *headers = [request allHTTPHeaderFields];
    if ([request.URL.absoluteString hasPrefix:@"https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb"]) {
        if (![[headers objectForKey:@"Referer"] isEqualToString:[NSString stringWithFormat:@"%@://",self.hostString]]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSURL *url = [request URL];
                NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
                [req setHTTPMethod:@"GET"];
                [req setValue:[NSString stringWithFormat:@"%@://",self.hostString] forHTTPHeaderField:@"Referer"];
                [webView loadRequest:req];
            });
        }
        return YES;
    } else{
        self.hostString = host;
    }
    if ([request.URL.absoluteString containsString:@"weixin://"]) {
        BOOL bSucc = [[UIApplication sharedApplication] openURL:request.URL];
        if (bSucc) {
            [[UIApplication sharedApplication] openURL:request.URL];
        } else {
            [SEGAlertView showTmepMessageWithMessage:@"未检测到微信客户端，请安装后重试。"];
        }
        return NO;
    }
    
    //跳转支付宝
    NSString* reqUrl = request.URL.absoluteString;
    if ([reqUrl hasPrefix:@"alipays://"] || [reqUrl hasPrefix:@"alipay://"] || [reqUrl hasPrefix:@"alipayqr://"]) {
        // NOTE: 跳转支付宝App
        BOOL bSucc = [[UIApplication sharedApplication] openURL:request.URL];
        if (!bSucc) {
            [SEGAlertView showTmepMessageWithMessage:@"未检测到支付宝客户端，请安装后重试。"];
        }
        return NO;
    }
    // 子类调用的方法，实现与业务挂钩
    return [super jsInvokeSystemFunctionWithWebView:webView request:request query:query];
}

/// URL地址参数替换
-(NSString*)segReplaceUrlStringWithUrlString:(NSString *)urlString{
    return [SEGWebViewLoadManager segReplaceUrlStringWithUrlString:urlString];
}
/// URL地址添加平台号
-(NSString*)getUrlStringWithAppPlatformCode:(NSString *)urlString{
    return [SEGPlatformManager getUrlStringWithAppPlatformCode:urlString];
}

-(void)requestFailWithWebView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    
    NSDictionary *params =@{@"view":self.view,
                            kNoDataText:@"哎呀！内容出不来了呢",
                            @"image":@"pic_default_error",
                            kNoDataBackgroundColor : kColor_W
    };
    [[SEGUhomeMediator sharedInstance] seg_showCustomProgressImage:params];
}

-(void)hideFailWithWebView:(WKWebView *)webView {
    [[SEGUhomeMediator sharedInstance] seg_hideCustomProgressImage:nil];
}

#pragma mark - 私有方法
/**
 销毁控制器内部控件
 */
-(void)destroyViews{
    [self setNavigationShow:SEGEnumNavigationBarShowType_System hasShare:NO];
    [self destroyNaviHeaderView];
    [self.headerView hideShare];
    //self.headerView.canShowCloseButton = NO;
    [self.headerView.headerScrollView setHidden:YES];
    
    [self.webView removeFromSuperview];
    [self.progressView removeFromSuperview];
    [self.naviHideHeaderView removeFromSuperview];
    
    //    self.webView = nil;
    //    self.progressView = nil;
    //    self.naviHideHeaderView = nil;
    //    self.currentUrl = nil;
}
/**
 初始化导航栏头部视图
 */
-(void)initNaviHeaderView{
    self.navigationItem.hidesBackButton = YES;
    self.headerView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 44);
    self.navigationItem.titleView = self.headerView;
}

/**
 销毁导航栏头部视图标题
 */
-(void)destroyNaviHeaderView{
    self.navigationItem.hidesBackButton = NO;
    [self.headerView removeFromSuperview];
    self.headerView = nil;
    self.navigationItem.titleView = nil;
}

-(void)webBackWithParams:(id)params{
    if (self.webView.canGoBack) {
        if (self.isDigitalComunity) {
            [self setNavigationShow:SEGEnumNavigationBarShowType_Custom hasShare:NO];
        }
        [self.webView goBack];
        return;
    }
    [self setNavigationShow:SEGEnumNavigationBarShowType_System hasShare:self.hasShareBtn];
    [self segPopVC];
}
/**
 设置导航栏显示或者隐藏
 
 @param show SEGEnumNavigationBarShowType
 @param hasShare 是否展示分享按钮
 */
-(void)setNavigationShow:(SEGEnumNavigationBarShowType)show hasShare:(BOOL)hasShare{
    //导航栏
    self.webView.frame = self.view.bounds;
    self.statusBarBackView.hidden = YES;
    if (show == SEGEnumNavigationBarShowType_System) {
        if (@available(iOS 11.0, *)) {
            self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.navigationController.navigationBarHidden = NO;
        [self.naviHideHeaderView setHidden:YES];
        [[NSUserDefaults standardUserDefaults]setObject:@(SEGEnumNavigationBarShowType_System) forKey:UserDefaultEnumNavigationBarShowTypeKey];
    }else if(show == SEGEnumNavigationBarShowType_Custom){
        if (@available(iOS 11.0, *)) {
            self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        self.edgesForExtendedLayout = UIRectEdgeAll;
        self.navigationController.navigationBarHidden = YES;
        [self.naviHideHeaderView setHidden:NO];
        self.naviHideHeaderView.backButtonImage = [UIImage imageWithContentsOfFile:SEGPicName(@"btn_header_back")];
        [[NSUserDefaults standardUserDefaults]setObject:@(SEGEnumNavigationBarShowType_Custom) forKey:UserDefaultEnumNavigationBarShowTypeKey];
    }else if (show == SEGEnumNavigationBarShowType_NONav) {
        if (@available(iOS 11.0, *)) {
            self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        self.edgesForExtendedLayout = UIRectEdgeAll;
        self.navigationController.navigationBarHidden = YES;
        [self.naviHideHeaderView setHidden:YES];
        
        [[NSUserDefaults standardUserDefaults]setObject:@(SEGEnumNavigationBarShowType_NONav) forKey:UserDefaultEnumNavigationBarShowTypeKey];
    }else{
        if (@available(iOS 11.0, *)) {
            self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAutomatic;
        }
        self.navigationController.navigationBarHidden = YES;
        self.edgesForExtendedLayout = UIRectEdgeNone;
        [self.naviHideHeaderView setHidden:YES];
        self.webView.y = LYStatusBarHeight();
        self.webView.height = LYScreenHeight() - LYStatusBarHeight();
        //隐藏导航栏的情况
        self.statusBarBackView.hidden = NO;
        [self setStatusBarBackgroundColor:[UIColor whiteColor]];
        [[NSUserDefaults standardUserDefaults]setObject:@(SEGEnumNavigationBarShowType_NO) forKey:UserDefaultEnumNavigationBarShowTypeKey];
    }
    
    //分享按钮
    if (hasShare){
        [self.headerView showShare];
        [self.naviHideHeaderView showShare];
        
    }else{
        [self.headerView hideShare];
        [self.naviHideHeaderView hideShare];
    }
}

-(void)segPopVC{
    [self setNavigationShow:SEGEnumNavigationBarShowType_System hasShare:NO];
    [self.navigationController popViewControllerAnimated:YES];
}


/**
 设置顶部状态栏颜色
 
 @param color UIColor
 */
- (void)setStatusBarBackgroundColor:(UIColor *)color {
    
    self.statusBarBackView.backgroundColor = color;
}

#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (object == self.webView && [keyPath isEqualToString:kvo_URL])  [self seg_keyPathURLWithChange:change];
}

/**
 监控WKWebView的URL属性，动态捕捉URL值
 
 @author Sam
 @param change change value
 */
-(void)seg_keyPathURLWithChange:(NSDictionary *)change{
    id changeNew = [change objectForKey:NSKeyValueChangeNewKey];
    id changeold = [change objectForKey:NSKeyValueChangeOldKey];
    
    if (changeNew && [changeNew isKindOfClass:[NSURL class]]) {
        self.currentUrl = changeNew;
    }else if (changeold && [changeold isKindOfClass:[NSURL class]]){
        self.currentUrl = changeold;
    }
    
    if (!self.headerView.headerScrollView.hidden) [self.headerView.headerScrollView resetItemStatusWithUrlString:self.currentUrl.absoluteString];
}

#pragma mark - JS交互

/**
 签名
 */
-(void)segJSSystemSignatureWithQuery:(NSString*)query request:(NSURL*)request image:(UIImage*)image{
    SEGUrlparamsModel * urlData = [SEGUrlparamsModel yy_modelWithJSON:query];
    
    NSData *imageData = [image adjustImageWithinLenght:1*1024*1024];//图片控制在1M
    NSString* imageLocalPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"Signature.jpg"];
    [imageData writeToFile:imageLocalPath atomically:YES];
    
    NSMutableDictionary *data = [NSMutableDictionary dictionary];
    [data setValue:[imageData base64EncodedString] forKey:@"base64"];
    [data setValue:imageLocalPath forKey:@"uri"];
    
    NSString *string = [NSString stringWithFormat:@"%@(%@)",urlData.fn,[@{@"code":@"1",@"message":@"",@"data":data} yy_modelToJSONString]];
    [self.webView evaluateJavaScript:string completionHandler:^(id _Nullable req, NSError * _Nullable error) {
    }];
}

/**
 商业改造-打开商品详情
 处理：根据传入的参数打开相应的详情页面
 
 Key:id
 Value:””//商品或活动id
 Key:type
 Value:”XXXX”//”1”为便利购，”2”是团购
 Key:fn
 Value:”fn”//回调时的函数名
 
 @author Sam
 @param query id=xxxx&type=xxx&fn=xxx
 */
-(void)segJSBusinessOpenActDetailWithQuery:(NSString*)query request:(NSURL*)request{
    NSMutableDictionary *data = [NSMutableDictionary dictionary];
    for (NSString *object in [query componentsSeparatedByString:@"&"]) { //[@"key=value",@"key=value",...]
        NSString *key = [[object componentsSeparatedByString:@"="] firstObject];
        NSString *value = [[object componentsSeparatedByString:@"="] lastObject];
        [data setValue:value forKey:key];
    }
    
    NSDictionary *params = @{@"serviceId":data[@"id"]};
    UIViewController *GroupsShoppingDetailVC = [[SEGUhomeMediator sharedInstance] seg_initGroupsShoppingDetailViewController:params];
    [self.navigationController pushViewController:GroupsShoppingDetailVC animated:YES];
    
    //if (self.completed) self.completed(data, request);
}

/**
 到家服务-设置标题栏标题，选中状态
 处理：根据参数设置标题栏
 
 {
 "isTransparent":"1", //1为透明，0为非透明样式
 "title":"aaa,bbb,cccc", //设置导航栏标题，有可能多个 逗号隔开
 "urls":"aaa,bbb,cccc", //上面标题对应的跳转路径
 "selected":"1", //选中的标题，按按照顺序，从1开始
 "hasShare":"1", 1为显示转发按钮，0为不显示
 "fn":"1" //返回函数
 }
 
 @author Sam
 @param query params={"isTransparent":"0","title":"aaa,bbb,cccc","urls":"aaa,bbb,cccc","selected":"1","hasShare":"1","fn":"1"}
 */
-(NSString*)segJSHomeserviceSetHeadTitleWithQuery:(NSString*)query{
    SEGUrlparamsModel * data = [SEGUrlparamsModel yy_modelWithJSON:query];
    
    if (![data.isTransparent isEqualToString:@"1"]) {
        NSArray *titlesArr = [data.title componentsSeparatedByString:@","];
        NSArray *urlsArr = [data.urls componentsSeparatedByString:@","];
        if (titlesArr && titlesArr.count > 0 && urlsArr && urlsArr.count > 0 && titlesArr.count == urlsArr.count && urlsArr.count >= data.selected.integerValue) {
            __block NSMutableArray *tmp = [NSMutableArray array];
            [urlsArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [tmp addObject:[NSString stringWithFormat:@"%@%@",@"",obj]];
            }];
            self.headerView.headerScrollView.hidden = NO;
            [self.headerView.headerScrollView restoreItemDataWithTitle:titlesArr urls:tmp selected:data.selected.integerValue];
            self.headerView.title = @"";
        }else{
            self.headerView.headerScrollView.hidden = YES;
            self.headerView.title = data.title;
        }
    }
    BOOL hasShare = [data.hasShare isEqualToString:@"1"] ? YES:NO;
    [self setNavigationShow:([data.isTransparent isEqualToString:@"1"] ? SEGEnumNavigationBarShowType_Custom : SEGEnumNavigationBarShowType_System) hasShare:hasShare];
    self.hasShareBtn = hasShare;
    return [NSString stringWithFormat:@"%@(%@)",data.fn,[@{@"code":@"1",@"message":@""} yy_modelToJSONString]];
}



/**
 设置分享参数
 处理：设置分享出去的参数
 
 {
 "icon":"url",  // 分享的图标的url
 "title":"标题"  //分享的标题
 }
 
 @author Sam
 @param query params={"icon":"1","title":"aaa"}
 */
-(void)segJSHomeserviceSetShareParaWithQuery:(NSString*)query{
    SEGUrlparamsModel * data = [SEGUrlparamsModel yy_modelWithJSON:query];
    if (!(data.icon.length > 0 && data.title.length > 0)) return;
    self.headerView.data = data;
    self.naviHideHeaderView.data = data;
}

/**
 客服跳转
 处理：根据传入的参数进入消息中心详情页
 
 {
 "providerSid":"1", //服务商id
 "serviceSid":"aaa,bbb,cccc", //服务id
 "type":"1", //用户所选择的服务规格或类型
 "fn":"1" //返回函数
 }
 
 @author Sam
 @param query params={"providerSid":"1","serviceSid":"aaa,bbb,cccc","type":"1","fn":"1"}
 */
-(void)segJSHomeserviceCounselingWithQuery:(NSString*)query request:(NSURL*)request{
    SEGUrlparamsModel * data = [SEGUrlparamsModel yy_modelWithJSON:query];
    //if (self.completed) self.completed(data, request);
    
    NSString* goMessage = [NSString stringWithFormat:@"100888|%@|%@|%@|%@", data.providerSid , data.serviceSid, data.type, kAccountUserID];
    
    NSDictionary *params = @{@"groupID":goMessage};
    UIViewController *vc = [[SEGUhomeMediator sharedInstance] seg_initOrderMessageViewController:params];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
    
}

/**
 确认订单页跳转
 处理：根据传入的参数进入确认订单页
 
 {
 "providerSid":"1", //服务商id
 "serviceSid":"aaa,bbb,cccc", //服务id
 "type":"1", //用户所选择的服务规格或类型
 "fn":"1" //返回函数
 }
 
 @author Sam
 @param query params={"providerSid":"1","serviceSid":"aaa,bbb,cccc","type":"1","fn":"1"}
 */
-(void)segJSHomeserviceConfirmOrderWithQuery:(NSString*)query request:(NSURL*)request{
    SEGUrlparamsModel * data = [SEGUrlparamsModel yy_modelWithJSON:query];
    //    if (self.completed) self.completed(data, request);
    
    NSDictionary *params = @{@"dataDic":[ data yy_modelToJSONObject]};
    UIViewController *OrderComfirmVC = [[SEGUhomeMediator sharedInstance] seg_initOrderComfirmViewController:params];
    [self.navigationController pushViewController:OrderComfirmVC animated:YES];
}


/**
 用户信息
 处理：获取用户基本信息，根据传入的数组获取相应的字段
 
 {
 "para":["userId","accessToken","deviceId","communityId","source","versionCode","phoneModel","systemVersionCode"]
 }
 
 @author Sam
 @param query params={"para":["userId","accessToken","deviceId","communityId","source","versionCode"],"fn":"uhomeNativeApi.getUserInfoCb"}
 @return uhomeNativeApi.getUserInfoCb({code:"",message:"",data:{"deviceId":"2D248A25-439B-4CA0-8BB2-7D5E6CC66DF9","source":"2","userId":"452613","communityId":"67","versionCode":"42"}})
 */
-(NSString*)segJSUserInfoGetWithQuery:(NSString*)query{
    NSString *jsString = [SEGWebViewLoadManager segJavaScriptStringFromUrlString:query];
    NSLog(@"%@",jsString);
    if (jsString && jsString.length > 0) return jsString;
    return @"";
}

/**
 使用原生系统功能：使用系统自带图片浏览器打开图片
 处理：根据传入的参数使用原生图片浏览器打开图片
 
 {
 "urls":"aaa,bbb,cccc", //图片json数组
 "index":"0,1,2" // 数字类型 当前图片的那个索引开始 0为第一个
 }
 
 @author Sam
 @param query params={"urls":"aaa,bbb,cccc","index":"0,1,2"}
 */
-(void)segJSSystemOpenImgViewerWithQuery:(NSString*)query{
    //SEGUrlparamsModel * data = [SEGUrlparamsModel yy_modelWithJSON:query];
    [[[UIAlertView alloc]initWithTitle:@"提示" message:@"此功能暂时不支持！" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil] show];
}

/**
 使用原生系统功能：把字符串添加到系统剪贴板
 处理：把字符串添加到系统剪贴板
 
 {
 "string":"string" //需要复制的字符串内容
 }
 
 @author Sam
 @param query params={"string":"string"}
 */
-(void)segJSSystemAddToClipboardWithQuery:(NSString*)query{
    SEGUrlparamsModel * data = [SEGUrlparamsModel yy_modelWithJSON:query];
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = data.string;
}

/**
 使用原生系统功能：跳转到原生页面
 处理：跳转到相关的原生页面
 
 寻常币页面：{"page":"MY_POINT","para":{"balanceType":"5"}}
 积分商城订单确认：{"page":"BONUSES_ORDER_CONFIRM","para":{"id":"xxx"}}
 广告页面：{"page":"ADVERTISEMENT","para":{"advertisingId":"广告id","typeId":"跳转类型id","href":"跳转路径","title":"标题"}}
 五星好评：{"page":"FIVE_STAR_RATING","para":{"quizTypeId":"xxx"}}
 优秀员工：{"page":"GOOD_STAFF","para":{"introId":"xxx"}}
 便民：{"page":"CONVENIENCE_SERVICE","para":{}}
 商圈：{"page":"BUSINESS_SERVICE","para":{}}
 房屋认证：{"page":"ASSETS_AUTHENTICATION","para":{}}
 
 @author Sam
 @param query params={"page":"string","para":{}}
 */
-(void)segJSSystemJumpToNativeWithQuery:(NSString*)query request:(NSURL*)request{
    SEGSystemnativeModel * data = [SEGSystemnativeModel yy_modelWithJSON:query];
    //    if (self.completed) self.completed(data, request);
    
    {
        
        NSString *page = data.page; //跳转页面code
        NSDictionary *paraDict = [data.para yy_modelToJSONObject];//跳转页面参数
        
        //积分页面
        if ([page isEqualToString:@"MY_POINT"]) {
            
            NSDictionary *params = @{@"banalceType":([paraDict objectForKey:@"balanceType"])};
            UIViewController *IntegralCashVC = [[SEGUhomeMediator sharedInstance] seg_initIntegralCashViewController:params];
            [self.navigationController pushViewController:IntegralCashVC animated:YES];
            return;
        }
        
        //积分商城订单确认
        if ([page isEqualToString:@"BONUSES_ORDER_CONFIRM"]) {
            
            NSDictionary *params = @{@"idString":ValueToString([paraDict objectForKey:@"id"])};
            UIViewController *VC = [[SEGUhomeMediator sharedInstance]seg_initIntegralExchangeConfirmViewController:params];
            [self.navigationController pushViewController:VC animated:YES];
            return;
        }
        
        //广告页面
        if ([page isEqualToString:@"ADVERTISEMENT"]) {
            //发送广告跳转通知
            NSDictionary* dict = @{
                @"typeId" : ValueToString([paraDict objectForKey:@"typeId"]),
                @"href" : ValueToString([paraDict objectForKey:@"href"]),
                @"title" : ValueToString([paraDict objectForKey:@"title"])
            };
            [[SEGUhomeMediator sharedInstance]seg_pushToViewControllerWithType:dict];
            return;
        }
        
        //住户好评
        if ([page isEqualToString:@"FIVE_STAR_RATING"]) {
            NSDictionary* dict = @{
                @"type" : @"0",
                @"action" : @"cn.segi.uhome.action.FIVESTAR"
            };
            [[SEGUhomeMediator sharedInstance]seg_pushToViewControllerWithAction:dict];
            
            return;
        }
        
        //优秀员工
        if ([page isEqualToString:@"GOOD_STAFF"]) {
            NSString *introId = [paraDict valueForKey:@"introId"];
            NSDictionary* dict = @{
                @"type" : @"0",
                @"action" : @"cn.segi.uhome.action.GOODSTAFF",
                @"introId" : ValueToString(introId)
            };
            [[SEGUhomeMediator sharedInstance]seg_pushToViewControllerWithAction:dict];
            return;
        }
        
        //便民
        if ([page isEqualToString:@"CONVENIENCE_SERVICE"]) {
            NSDictionary* dict = @{
                @"type" : @"0",
                @"action" : @"cn.segi.uhome.action.PAGE"
            };
            [[SEGUhomeMediator sharedInstance]seg_pushToViewControllerWithAction:dict];
            return;
        }
        
        //商圈
        if ([page isEqualToString:@"BUSINESS_SERVICE"]) {
            NSDictionary* dict = @{
                @"type" : @"0",
                @"action" : @"cn.segi.uhome.action.BUSINESS_CIRCLE"
            };
            [[SEGUhomeMediator sharedInstance]seg_pushToViewControllerWithAction:dict];
            return;
        }
        
        //数字社区
        if ([page isEqualToString:@"ASSETS_AUTHENTICATION"]) {
            UIViewController *VC = [[SEGUhomeMediator sharedInstance]seg_initDigitalComRootViewController:nil];
            [self.navigationController pushViewController:VC animated:YES];
            
            return;
        }
    }
}

/**
 使用原生系统功能：批量上传文件
 处理：调用原生上传图片或文件接口，最后返回图片服务器路径列表给H5。
 常服务需判断文件类型，如果是图片则调用图片专用的上传接口，如果是其他文件则调用其他文件上传接口。
 目前没有区分接口，暂不使用该逻辑。serviceType用在有单独区分开的图片服务器的定制服务上，如到家汇、慧到家。
 
 {
 "fn":"xxx",//返回函数名
 "para":{
 "serviceType":"xxx",   //0：b端服务，1：c端服务
 "uri":["xxx","xxx"]    //文件本地图片路径
 }
 }
 
 @author Sam
 @param query params={"fn":"fn","para":{"serviceType":"xxx","uri":["xxx","xxx"]}}
 */
-(void)segJSSystemUploadFilesWithQuery:(NSString*)query request:(NSURL*)request{
    SEGSystemnativeModel * data = [SEGSystemnativeModel yy_modelWithJSON:query];
    __block NSMutableArray<NSData*> *paramsDataArrM = [NSMutableArray array];
    __block NSMutableArray<SEGUploadFileModel *> *fileModelArr = [NSMutableArray array];
    __block BOOL isImage;
    [data.para.uri enumerateObjectsUsingBlock:^(NSString*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSArray * stringType = [obj componentsSeparatedByString:@"."];
        NSString * type = stringType.lastObject;
        type = type.lowercaseString;
        if ([type isEqualToString:@"bmp"] || [type isEqualToString:@"jpg"] || [type isEqualToString:@"jpge"] || [type isEqualToString:@"png"] || [type isEqualToString:@"gif"]){
            isImage = YES;
            //            NSData *localData = [NSData dataWithContentsOfFile:obj];
            //            if (localData) [paramsDataArrM addObject:localData];
            
            UIImage *localImage = [UIImage imageWithContentsOfFile:obj];
            if (localImage) {
                NSData *zipData = [UIImage seg_zipImageWithImage:localImage withCompressionQuality:1];
                if (zipData) {
                    [paramsDataArrM addObject:zipData];
                }
            }
            
        }else {
            isImage = NO;
            SEGUploadFileModel *model = [SEGUploadFileModel new];
            model.data = [NSData dataWithContentsOfFile:obj];
            model.fileName = obj;
            model.mimeType = @"application/octet-stream";
            [fileModelArr addObject:model];
        }
    }];
    
    if (isImage) {
        if (paramsDataArrM.count <=0) {
            NSString *js = [NSString stringWithFormat:@"%@(%@)",data.fn,[@{@"code":@"0",@"message":@"本地不存在图片缓存，请重新上传！",@"data":@""} yy_modelToJSONString]];
            [self.webView evaluateJavaScript:js completionHandler:^(id _Nullable req, NSError * _Nullable error) {
            }];
            return;
        }
        
        //图片上传到服务器
        //uploadType=1 代表需要进行人脸识别校验 只上传第一张图片
        if (data.para.uploadType.integerValue == 1) {
            [SVProgressHUD show];
            UIImage *firstImage = [UIImage imageWithData:paramsDataArrM.firstObject];
            [[SEGOnefileuploadManager sharedManager] requestImageUploadToCheckFaceDetection:firstImage serviceType:data.para.serviceType completed:^(BOOL isSuccessed, id result, NSString *codeType, NSError *error) {
                [SVProgressHUD dismiss];
                if ([codeType isEqualToString:@"-1"]) {
                    NSMutableDictionary *params = [NSMutableDictionary dictionary];
                    [params setValue: @"0" forKey:@"code"];
                    [params setValue: error.localizedDescription forKey:@"message"];
                    NSString *js = [NSString stringWithFormat:@"%@(%@)",data.fn,[params yy_modelToJSONString]];
                    [self.webView evaluateJavaScript:js completionHandler:^(id _Nullable req, NSError * _Nullable error) {
                    }];
                    // [SEGAlertView showTmepMessageWithMessage:errorMessage];
                }else{
                    NSMutableDictionary *params = [NSMutableDictionary dictionary];
                    [params setValue: isSuccessed ? @"1" : @"0" forKey:@"code"];
                    [params setValue:result[@"message"] ?: @"" forKey:@"message"];
                    NSString *uploadImageURL = result[@"data"] ?: @"";
                    [params setValue:@{@"urls": @[uploadImageURL]} forKey:@"data"];
                    NSString *js = [NSString stringWithFormat:@"%@(%@)",data.fn,[params yy_modelToJSONString]];
                    [self.webView evaluateJavaScript:js completionHandler:^(id _Nullable req, NSError * _Nullable error) {
                    }];
                }
            }];
            return;
        }
        
        [SVProgressHUD show];
        [[SEGMultipartfileuploadManager sharedManager] requestH5MultipartfileuploadWithData:paramsDataArrM serviceType:data.para.serviceType progress:^(double progressValue) {
            dispatch_async(dispatch_get_main_queue(), ^{
                //[self seg_keyPathEstimatedProgressWithChange:progressValue];
            });
        } completed:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            [SVProgressHUD dismiss];
            if ([codeType isEqualToString:@"-1"]) {
                NSMutableDictionary *params = [NSMutableDictionary dictionary];
                [params setValue: @"0" forKey:@"code"];
                [params setValue: errorMessage forKey:@"message"];
                NSString *js = [NSString stringWithFormat:@"%@(%@)",data.fn,[params yy_modelToJSONString]];
                [self.webView evaluateJavaScript:js completionHandler:^(id _Nullable req, NSError * _Nullable error) {
                }];
                // [SEGAlertView showTmepMessageWithMessage:errorMessage];
            }else{
                NSMutableDictionary *params = [NSMutableDictionary dictionary];
                [params setValue: isSuccessed ? @"1" : @"0" forKey:@"code"];
                [params setValue:[SEGMultipartfileuploadManager sharedManager].multipartFileUpload.message forKey:@"message"];
                if ([SEGMultipartfileuploadManager sharedManager].multipartFileUpload.data.count > 0) {
                    [params setValue:@{@"urls":[SEGMultipartfileuploadManager sharedManager].multipartFileUpload.data} forKey:@"data"];
                }
                NSString *js = [NSString stringWithFormat:@"%@(%@)",data.fn,[params yy_modelToJSONString]];
                [self.webView evaluateJavaScript:js completionHandler:^(id _Nullable req, NSError * _Nullable error) {
                }];
            }
        }];
        
        //        [[SEGMultipartfileuploadManager sharedManager] requestMultipartfileuploadWithData:paramsDataArrM serviceType:data.para.serviceType progress:^(double progressValue) {
        //            dispatch_async(dispatch_get_main_queue(), ^{
        //                //[self seg_keyPathEstimatedProgressWithChange:progressValue];
        //            });
        //        } completed:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        //            NSMutableDictionary *params = [NSMutableDictionary dictionary];
        //            [params setValue: isSuccessed ? @"1" : @"0" forKey:@"code"];
        //            [params setValue:[SEGMultipartfileuploadManager sharedManager].multipartFileUpload.message forKey:@"message"];
        //            if ([SEGMultipartfileuploadManager sharedManager].multipartFileUpload.data.count > 0) {
        //                [params setValue:@{@"urls":[SEGMultipartfileuploadManager sharedManager].multipartFileUpload.data} forKey:@"data"];
        //
        //                NSString *js = [NSString stringWithFormat:@"%@(%@)",data.fn,[params yy_modelToJSONString]];
        //                [self.webView evaluateJavaScript:js completionHandler:^(id _Nullable req, NSError * _Nullable error) {
        //                }];
        //            }
        //        }];
    }else {
        //其他文件上传到服务器
        if (fileModelArr.count <= 0) {
            return;
        }
        __weak typeof (self) weakSelf = self;
        [SVProgressHUD show];
        [[SEGUploadmultipartfileManager sharedManager] requestDatasWithDetailData:fileModelArr progress:^(double progressValue) {
            dispatch_async(dispatch_get_main_queue(), ^{
            });
        } completed:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            [SVProgressHUD dismiss];
            SEGUploadmultipartfileModel *model = [SEGUploadmultipartfileManager sharedManager].uploadMultipartFile;
            NSMutableDictionary *params = [NSMutableDictionary dictionary];
            [params setValue: isSuccessed ? @"1" : @"0" forKey:@"code"];
            [params setValue:model.message forKey:@"message"];
            if (model.data.count > 0) {
                [params setValue:@{@"urls":model.data} forKey:@"data"];
                NSString *js = [NSString stringWithFormat:@"%@(%@)",data.fn,[params yy_modelToJSONString]];
                [self.webView evaluateJavaScript:js completionHandler:^(id _Nullable req, NSError * _Nullable error) {
                }];
            }
        }];
    }
}

/**
 使用原生系统功能：隐藏原生头部导航栏
 处理：隐藏原生头部导航栏
 
 空
 
 @author Sam
 @param query 空
 */
-(void)segJSSystemHideHeaderWithQuery:(NSString*)query{
    [self setNavigationShow:SEGEnumNavigationBarShowType_NO hasShare:NO];
}

/**
 使用原生系统功能：分享到社交平台
 处理：根据传入的参数区别不同的分享方式，原生实现分享页面url
 
 {
 "title":"xxx", //标题，默认为
 "icon":"xxx", //分享的缩略图
 "content":"xxx", //选中的标题的index 从1开始
 "url":"xxx" //分享的连接url,默认为当前url
 "channel":"sms,mini" // sms:短信 wechat:微信 mini:微信小程序 friends: 朋友圈 qq: 腾讯QQ
 "options": {
 "sms": {"content":"短信内容"},
 "mini": {"miniprogtamType":"0",// 0 正式版 1 测试版 2 体验版
 "userName":"小程序原始ID",
 "path":"小程序页面路径",
 },
 
 }
 }
 
 @author Sam
 @param query params={"title":"xxx","icon":"xxx","content":"xxx","url":"xxx"}
 */
-(void)segJSSystemSocialShareWithQuery:(NSString*)query request:(NSURL*)request{
    //分享逻辑处理
    if (!query) return;
    SEGUrlparamsModel * data = [SEGUrlparamsModel yy_modelWithJSON:query];
    if (data.channel && data.channel.length > 0) {
        
        NSData *jsonData = [query dataUsingEncoding:NSUTF8StringEncoding];
        if (!jsonData) return;
        
        NSDictionary *queryDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:NULL];
        if (!(queryDic && [queryDic isKindOfClass:[NSDictionary class]] && [[queryDic allKeys] count] > 0)) return;
        
        NSMutableDictionary *shareInputPar = [NSMutableDictionary dictionary];
        
        [shareInputPar setValue:[queryDic valueForKey:@"title"] forKey:@"sharetitle"];
        [shareInputPar setValue:[queryDic valueForKey:@"content"] forKey:@"sharecontent"];
        [shareInputPar setValue:[queryDic valueForKey:@"url"] forKey:@"inviteurl"];
        NSString *icon = [queryDic valueForKey:@"icon"];
        if (icon && icon.length > 0) [shareInputPar setValue:[NSString stringWithFormat:@"%@%@",kClientImageRootURL,icon] forKey:@"shareImageUrlString"];
        
        NSDictionary *options = [queryDic valueForKey:@"options"];
        
        NSString *channel = [queryDic valueForKey:@"channel"];
        if (!(channel && [channel isKindOfClass:[NSString class]] && channel.length > 0)) return;
        
        NSMutableArray *channelArr = [NSMutableArray array];
        for (NSString *object in [channel componentsSeparatedByString:@","]) {
            if([object isEqualToString:@"sms"]) [channelArr addObject:@(SEGShareVCActionType_Share_Message)];//sms:短信
            if([object isEqualToString:@"wechat"]) [channelArr addObject:@(SEGShareVCActionType_Share_WeChat)];//wechat:微信
            if([object isEqualToString:@"friends"]) [channelArr addObject:@(SEGShareVCActionType_Share_FriendCircle)];//friends: 朋友圈
            if([object isEqualToString:@"qq"]) [channelArr addObject:@(SEGShareVCActionType_Share_QQ)];//qq: 腾讯QQ
            if([object isEqualToString:@"mini"]) {//mini:微信小程序
                [channelArr addObject:@(SEGShareVCActionType_MiniProgram_WeChat)];
                [shareInputPar setValue:[options valueForKey:@"mini"] forKey:@"miniapp"];
            }
        }
        
        [shareInputPar setValue:channelArr forKey:@"shareTypesArr"];
        [shareInputPar setValue:@"2" forKey:@"shareTypesArrType"];
        
        UIViewController* shareVC = [[SEGUhomeMediator sharedInstance] seg_initShareViewController:shareInputPar actionType:^(NSInteger actionType) {
            // 短信
            if (actionType == SEGShareVCActionType_Share_Message) {
                Class messageClass = (NSClassFromString(@"MFMessageComposeViewController"));
                if (messageClass != nil) {
                    if ([messageClass canSendText]) {
                        MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];
                        picker.messageComposeDelegate = self;
                        NSDictionary *smsDic = [options valueForKey:@"sms"];
                        NSString *smsBody = [smsDic valueForKey:@"content"];
                        picker.body = smsBody;
                        picker.title = [queryDic valueForKey:@"title"];
                        picker.modalPresentationStyle = UIModalPresentationFullScreen;
                        [[[UIApplication sharedApplication] keyWindow].rootViewController presentViewController:picker animated:YES completion:^{
                        }];
                    } else {
                        [[[UIAlertView alloc] initWithTitle:@"" message:@"设备不支持短信功能" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil] show];
                    }
                }
            }
            
        } channel:^(NSString *channel) {
            
        }];
        if (shareVC) {
            [self presentViewController:shareVC animated:NO completion:^{
            }];
        }
        
    }else{
        SEGUrlparamsModel * data = [SEGUrlparamsModel yy_modelWithJSON:query];
        //if (self.completed) self.completed(data,request);
        
        
        NSString *imageUrl = [NSString stringWithFormat:@"%@%@",kClientImageRootURL,data.icon];
        NSDictionary *parsma = @{
            @"sharetitle": data.title,
            @"sharecontent": data.content,
            @"shareTypesArrType":@"1",
            @"inviteurl": data.url,
        };
        NSMutableDictionary *tmp = [NSMutableDictionary dictionaryWithDictionary:parsma];
        if (data.icon && data.icon.length > 0) [tmp setValue:imageUrl forKey:@"shareImageUrlString"];
        
        UIViewController* shareVC = [[SEGUhomeMediator sharedInstance] seg_initShareViewController:tmp actionType:^(NSInteger actionType) {
            
        } channel:^(NSString *channel) {
            
        }];
        [self presentViewController:shareVC animated:NO completion:^{
        }];
    }
}

/**
 第三方使用api：跳转到支付列表
 处理：根据传入的参数跳转到支付列表页，支付成功后跳转到相关url
 
 {
 "url":"xxx", //支付成功后跳转地址
 "id":"xxx" //订单号
 }
 
 @author Sam
 @param query params={"url":"xxx","id":"xxx"}
 */
-(void)segJSThirdpartyGoPayListWithQuery:(NSString*)query request:(NSURL*)request{
    SEGUrlparamsModel * data = [SEGUrlparamsModel yy_modelWithJSON:query];
    qch_backUrl = data.cbUrl;
    NSDictionary *param = @{
        @"payTypeName": @(SEGPayTypeName_QiaoChengHui),
        @"orderIdOracctItemIds":data.orderID
    };
    [[SEGUhomeMediator sharedInstance] seg_sendPayForQiaoChengHuiWithParams:param];
}

/**
 第三方使用api：支付
 处理：根据传入的参数跳转到支付页面，支付成功后跳转到相关url
 
 ============微信============
 {
 "payCode":"WEIXIN",
 "cbUrl":"xxx",
 "payInfo":{
 "partnerid":"value",
 "prepayid":"value",
 "noncestr":"value",
 "timestamp":"value",
 "package":"value",
 "sign":"value"
 }
 }
 ============鹏华============
 {
 "payCode":" PENGHUA",
 "cbUrl":"xxx",
 "payInfo":{
 "payerId":"value",
 "vpayId":"value",
 "desc":"value",
 "addInfo":"value",
 "notifyUrl":"value",
 "amount":"value",
 "pHCallbackUrl":"value",
 "communityId":"value",
 "businessType":"value"
 }
 }
 
 @author Sam
 @param query params={"payCode":"WEIXIN","cbUrl":"xxx","payInfo":{"partnerid":"value","prepayid":"value","noncestr":"value","timestamp":"value","package":"value","sign":"value"}}
 */
-(void)segJSThirdpartyPayWithQuery:(NSString*)query request:(NSURL*)request{
    SEGUrlparamsModel * data = [SEGUrlparamsModel yy_modelWithJSON:query];
    //if (self.completed) self.completed(data,request);
    
    qch_backUrl = data.cbUrl;
    self.payType = SEGPayTypeName_CMHK_PayOnLine;
    
    NSDictionary *payInfo = [data.payInfo yy_modelToJSONObject];
    NSDictionary *param = @{
        @"dict": payInfo?payInfo:@{},//加个保护 防止payinfo weinil
        @"payCode": ValueToString(data.payCode),
        @"payChannel": ValueToString(data.payChannel)
    };
    [[SEGUhomeMediator sharedInstance] seg_initPayAction:param];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(getOrderPayResult:)
                                                 name:@"ORDER_PAY_NOTIFICATION" object:nil];
    
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(getBoHaiPayResult:)
     name:@"NSNotificationCenterName_BOHAI"
     object:nil];
}

- (void)getOrderPayResult:(NSNotification*)notification
{
    if ([notification.object isEqualToString:@"success"]) {
        if (self.payType == SEGPayTypeName_CMHK_PayOnLine) {
            if (qch_backUrl.length > 0) {
                qch_backUrl = [SEGWebViewLoadManager segReplaceUrlStringWithUrlString:qch_backUrl];
                [self loadDataWithURLString:qch_backUrl];
            }
        }
    }
}

/**
 渤海支付异步通知结果
 @author Sam
 @
 */
-(void)getBoHaiPayResult:(NSNotification*)notification {
    
    if (notification && [notification.userInfo isKindOfClass:[NSDictionary class]]) {
        
        NSDictionary *userInfo = notification.userInfo;
        NSString *code = [userInfo valueForKey:@"code"];
        NSString *msg = [userInfo valueForKey:@"msg"];

        // 支付成功！
        if (code && [code isKindOfClass:[NSString class]] && [code isEqualToString:@"1"]) {
            if (qch_backUrl.length > 0) {
                qch_backUrl = [SEGWebViewLoadManager segReplaceUrlStringWithUrlString:qch_backUrl];
                [self loadDataWithURLString:qch_backUrl];
            }
            return;
        }
        
        // 支付失败！
        if (msg && [msg isKindOfClass:[NSString class]] && msg.length > 0) {
            [SEGAlertView showTmepMessageWithMessage:msg];
        }
    }
}

/**
 第三方使用微信小程序
 处理：根据传入的参数跳转到小程序
 */

- (void)segJSThirdpartyMiniProgramWithQuery:(NSString*)query {
    
    NSData *jsonData = [query dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if (err) {
        NSLog(@"json解析失败：%@",err);
        [SVProgressHUD showInfoWithStatus:err.localizedDescription];
        return ;
    }
    
    [[SEGUhomeMediator sharedInstance] seg_initMiniProgram:@{@"dataDic":dic}];
}

/**
 第三方使用api：拍照
 处理：拍照, 把拍照照片转成base64 string通过回调函数参数方式回传
 
 {
 "fn":"funcname",//返回函数名
 "number":"1", //一次选择的图片数量
 "editable":"1" //0为不可编辑，1为可编辑 默认1
 }
 
 @author Sam
 @param query params={"fn":"xxx","number":"xxx","editable":"1"}
 */
-(void)segJSThirdpartyTakePhotoWithQuery:(NSString*)query{
    [self seg_UsePhotoAlbumAndCamera];
}

/**
 使用原生系统功能：相机
 处理：调用相机或者相册功能，把照片转成base64 string和文件的uri通过回调函数参数方式回传
 
 {
 "fn":"xxx",
 "para":{
 "number":"xxx", // 数字类型 选择图片的数量 默认1
 "editale":"xxx", // 数字类型 是否可编辑 1为可编辑 0为不可编辑
 "type":"xxx" // 数字类型 标识是什么调用类型 0 为可以拍照，可以从相册获取；1为只能拍照 ；2为只能从相册选。 默认为0
 }
 }
 
 @author Sam
 @param query params={"fn":"xxx","para":{"number":"xxx","editale":"xxx","type":"xxx"}}
 */
-(void)segJSSystemCameraWithQuery:(NSString*)query request:(NSURL*)request{
    SEGSystemnativeModel * data = [SEGSystemnativeModel yy_modelWithJSON:query];
    
    if (data && [data.para.type isEqualToString:@"1"]) {//拍照
        [self seg_UseCamera];
        
    }else if (data && [data.para.type isEqualToString:@"2"]){//相册
        [self seg_UsePhotoAlbum:data.para.number.integerValue];
    }else{//拍照&相册
        maxPhoto = data.para.number.integerValue;
        [self seg_UsePhotoAlbumAndCamera];
    }
}

/**
 第三方使用api：返回native界面
 处理：跳转到相关的原生页面
 
 空
 
 @author Sam
 @param query params={}
 */
-(void)segJSThirdpartyGoBackWithQuery:(NSString*)query{
    [self.navigationController popViewControllerAnimated:YES];
    // 应H5端 go(-1) 问题，直接返回原生
    //[self webBackWithParams:query];
}

/**
 第三方使用api：弹出确认框
 处理：弹出确认框，返回用户选择的操作
 
 {
 "fn":"funcname", //返回函数名
 "title":"xxx", //标题
 "content":"xxx", //提示内容
 "type":"0" // 0 有取消 有确定; 1 只有确定； 2 只有取消。 默认0
 }
 
 @author Sam
 @param query params={"fn":"0","title":"xxx","content":"xxx","type":"xxx"}
 */
-(void)segJSThirdpartyOpenDialogWithQuery:(NSString*)query{
    SEGUrlparamsModel * data = [SEGUrlparamsModel yy_modelWithJSON:query];
    
    UIAlertView *alert;
    if ([data.type isEqualToString:@"1"]) {
        alert = [[UIAlertView alloc] initWithTitle:data.title message:data.content delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    }else if ([data.type isEqualToString:@"2"]){
        alert = [[UIAlertView alloc] initWithTitle:data.title message:data.content delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
    }else{
        alert = [[UIAlertView alloc] initWithTitle:data.title message:data.content delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    }
    [alert show];
}

/**
 使用原生系统功能：批量获取本地文件
 处理：调用相机或者相册功能，把照片转成base64 string和文件的uri通过回调函数参数方式回传
 
 {
 fn: ‘xxxx’, // 返回函数名
 para: {
 number: 1 // 选择文件数量
 }
 }
 
 @author Wendy
 @param query params={"para":{"number":3},"fn":"uhomeNativeApi.takeFilesCb"}
 */
-(void)segJSSystemTakeFilesWithQuery:(NSString*)query request:(NSURL*)request{
    UIDocumentMenuViewController * importMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
    importMenu.delegate = self;
    importMenu.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:importMenu animated:YES completion:nil];
}




/**
 获取cookie
 
 @param url url
 */
- (void)seg_getCookieWithURL:(NSString *)url {
    
    NSRange rang = [url rangeOfString:@"="];
    if (rang.location == NSNotFound) {
        return;
    }
    
    NSArray *cookies = [[NSHTTPCookieStorage  sharedHTTPCookieStorage] cookies];
    NSDictionary * cookiesDic = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
    NSString *cookieString = cookiesDic[@"Cookie"] ?: @"";
    NSDictionary *result = @{@"code":@(1), @"data": cookieString};
    
    NSString *params = [url substringFromIndex:rang.location + 1];
    // 字符串转字典 为了获取其中的key：fn 对应的值
    
    NSDictionary* fnDict = [SEGUtils dictionaryWithJsonString:[params stringByRemovingPercentEncoding]];
    NSString* jsonStr = [result jsonPrettyStringEncoded] ?: @"";
    
    //注入js代码
    NSString *str = [NSString stringWithFormat:@"%@(%@)",[fnDict objectForKey:@"fn"],jsonStr];
    NSString *javaScript = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    [self.webView evaluateJavaScript:javaScript completionHandler:^(id _Nullable req, NSError * _Nullable error) {
    }];
}

#pragma mark - 选择本地文件、上传
- (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
{
    documentPicker.delegate = self;
    documentPicker.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:documentPicker animated:YES completion:nil];
}

-(void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
{
    [controller dismissViewControllerAnimated:YES completion:nil];
    [self upLoadFile:url];
}

-(void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
{
}

-(void)upLoadFile:(NSURL *)fileUrl
{
    NSString * string_iCloud = fileUrl.absoluteString.stringByRemovingPercentEncoding;
    NSArray * stringArr = [string_iCloud componentsSeparatedByString:@"/"];
    NSString * pathString = stringArr.lastObject;
    NSString * pathLocal = [SEGWebViewLoadManager getLocalPathByPath:pathString];
    
    SEGDocument *doc =[[SEGDocument alloc] initWithFileURL:fileUrl];
    
    [doc openWithCompletionHandler:^(BOOL success) {
        if (success) {
            // 读取数据成功
            BOOL LimitOk = YES;
            long long MaxMB = 5 * 1024 * 1024;//大小限制5M
            if (doc.myData.length > MaxMB) {
                [SEGAlertView showTmepMessageWithMessage:[NSString stringWithFormat:@"选择的文件大小不可超过%dMB，请重新选择",5]];
                LimitOk = NO;
            }
            if(!LimitOk){
                return;
            }
            
            BOOL isSave = [doc.myData writeToFile:pathLocal atomically:YES];
            if (isSave) {
                // 保存入本地成功
                __block NSMutableArray<NSString*>* tmp = [NSMutableArray array];
                [tmp addObject:pathLocal];
                if (tmp.count <= 0) return;
                
                NSDictionary *params = @{
                    @"code": @"1",
                    @"message": @"",
                    @"data": tmp //本地文件路径，数组
                };
                
                SEGUrlparamsModel * js = [SEGUrlparamsModel yy_modelWithJSON:[[self.currentUrl.query stringByURLDecode] stringByReplacingOccurrencesOfString:@"params=" withString:@""]];
                
                [self.webView evaluateJavaScript:[NSString stringWithFormat:@"%@(%@);",js.fn,[params yy_modelToJSONString]] completionHandler:^(id _Nullable req, NSError * _Nullable error) {
                }];
            }
            
        }
    }];
}
#pragma mark - MFMessageComposeViewControllerDelegate
- (void)messageComposeViewController:(MFMessageComposeViewController*)controller didFinishWithResult:(MessageComposeResult)result {
    [controller dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    SEGUrlparamsModel * data = [SEGUrlparamsModel yy_modelWithJSON:[[self.current_uhomeoc_href.query stringByURLDecode] stringByReplacingOccurrencesOfString:@"params=" withString:@""]];
    NSMutableDictionary *ret = [NSMutableDictionary dictionary];
    [ret setObject:@"1" forKey:@"code"];//1为成功，0为失败
    [ret setObject:data.content forKey:@"message"]; //提示语
    
    //0 有取消 有确定; 1 只有确定； 2 只有取消。 默认0
    if ([data.type isEqualToString:@"1"]) {
        [ret setObject:@"1" forKey:@"data"]; //0为取消1为确认
    }else if ([data.type isEqualToString:@"2"]){
        [ret setObject:@"0" forKey:@"data"]; //0为取消1为确认
    }else{
        if (buttonIndex == 0){
            [ret setObject:@"0" forKey:@"data"]; //0为取消1为确认
        }else{
            [ret setObject:@"1" forKey:@"data"]; //0为取消1为确认
        }
    }
    
    //funcname({"code":"0","message":"xxx","data":"0"})
    [self.webView evaluateJavaScript:[NSString stringWithFormat:@"%@(%@)",data.fn,[ret yy_modelToJSONString]] completionHandler:^(id _Nullable req, NSError * _Nullable error) {
    }];
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0:{ //相册
            [self seg_UsePhotoAlbum:maxPhoto];
            break;
        }
        case 1:{ //相机
            [self seg_UseCamera];
            break;
        }
        default:
            break;
    }
}

/**
 唤起相机功能
 */
-(void)seg_UseCamera{
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {//判断是否有相机
        self.imagePicker = [[SEGImagePickerManager alloc] init];
        self.imagePicker.delegate = self;
        self.imagePicker.sourceType = SEGImagePickerManagerSourceTypeCamera;
        self.imagePicker.allowsEditing = NO;
        [self.imagePicker presentImagePickerControllerWithAnimated:YES completion:nil];
    }
    else {
        [[[UIAlertView alloc]initWithTitle:@"提示" message:@"该设备无摄像头" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil] show];
    }
}

/**
 唤起系统相册功能
 */
-(void)seg_UsePhotoAlbum:(NSInteger)number{
    self.imagePicker = [[SEGImagePickerManager alloc] init];
    self.imagePicker.delegate = self;
    self.imagePicker.sourceType = SEGImagePickerManagerSourceTypePhotoLibrary;
    self.imagePicker.allowsEditing = NO;
    self.imagePicker.maxImagesCount = number <= 0 ? 1 : number;
    [self.imagePicker presentImagePickerControllerWithAnimated:YES completion:nil];
}


/**
 使用相机、相册
 */
-(void)seg_UsePhotoAlbumAndCamera{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"添加图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从手机选择",@"相机",nil];
    [actionSheet showFromTabBar:self.navigationController.tabBarController.tabBar];
}

-(void)saveImageToLocal:(NSArray<UIImage*>*)data{
    
    __block NSMutableArray<NSDictionary*>* tmp = [NSMutableArray array];
    [data enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSData *imageData = [obj adjustImageWithinLenght:1*1024*1024];//图片控制在1M
        NSString *fileName = [NSString stringWithFormat:@"WebTmpImage_%@_%zd.jpg",[NSDate getCurrentTimeTimestamp:SEGEnumTimerstamp_MilliSecond],idx];
        NSString* imageLocalPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:fileName];
        [imageData writeToFile:imageLocalPath atomically:YES];
        
        [tmp addObject:@{@"uri":imageLocalPath, @"base64":[imageData base64EncodedString]}];
    }];
    
    if (tmp.count <= 0) return;
    
    NSDictionary *params = @{
        @"code": @"1",
        @"message": @"",
        @"data": tmp//图片base64 string
    };
    
    SEGUrlparamsModel * js = [SEGUrlparamsModel yy_modelWithJSON:[[self.current_uhomeoc_href.query stringByURLDecode] stringByReplacingOccurrencesOfString:@"params=" withString:@""]];
    
    [self.webView evaluateJavaScript:[NSString stringWithFormat:@"%@(%@);",js.fn,[params yy_modelToJSONString]] completionHandler:^(id _Nullable req, NSError * _Nullable error) {
    }];
}

#pragma mark - SEGImagePickerManagerDelegate
- (void)seg_imagePickerManager:(SEGImagePickerManager *)manager didFinishPickingPhotos:(NSArray<UIImage *> *)photos assets:(NSArray<PHAsset *> *)assets isSelectOriginalPhoto:(BOOL)isSelect {
    
    [self saveImageToLocal:photos];
}

- (void)seg_imagePickerManagerDidCancel:(SEGImagePickerManager *)picker {
    
}

#pragma mark - SEGSEGNaviHeaderViewProtocol
-(void)segbackBtnClick{
    [self webBackWithParams:nil];
}

-(void)shareBtnClick:(id)data{
    if (data && [data isKindOfClass:[SEGUrlparamsModel class]]) {
        SEGUrlparamsModel *ret = (SEGUrlparamsModel*)data;
        //if (self.completed) self.completed(ret, [NSURL URLWithString:@"uhomeoc://homeservice.setSharePara"]);
        //拼接应用的scheme
        NSString *shareUrl;
        if ([self.currentUrl.absoluteString rangeOfString:@"?"].location == NSNotFound) {
            //没有任何参数时 用？拼接
            shareUrl = [NSString stringWithFormat:@"%@?scheme=%@",self.currentUrl.absoluteString ,kOpenAppScheme];
        }else {
            shareUrl = [NSString stringWithFormat:@"%@&scheme=%@",self.currentUrl.absoluteString,kOpenAppScheme];
        }
        shareUrl = [SEGPlatformManager getUrlStringWithAppPlatformCode:shareUrl];
        
        NSDictionary *parsma = @{
            @"sharetitle": ret.title,
            @"sharecontent": [NSString stringWithFormat:@"我在%@发现了一个好东西，用积分就能兑换。",kAppName],
            @"inviteurl": shareUrl,
            @"shareTypesArrType":@"1",
        };
        NSMutableDictionary *tmp = [NSMutableDictionary dictionaryWithDictionary:parsma];
        if (ret.icon && ret.icon.length > 0) [tmp setValue:[NSString stringWithFormat:@"%@%@",kClientImageRootURL,ret.icon] forKey:@"shareImageUrlString"];
        
        UIViewController* shareVC = [[SEGUhomeMediator sharedInstance] seg_initShareViewController:tmp actionType:^(NSInteger actionType) {
            
        } channel:^(NSString *channel) {
            
        }];
        [self presentViewController:shareVC animated:NO completion:nil];
    }
}

-(void)segcloseBtnClick{
    [self segPopVC];
}

#pragma mark - SEGNaviHeaderScrollViewProtocol
-(void)responseWithUrl:(NSString*)url{
    // TODO: 网页组件替换，这里需要进行改造！
    //从backForwardList历史记录中，跳转到已经缓存中的网页。
    /*
     
     __block BOOL hasBackRecord = NO;
     [self.webView.backForwardList.backList enumerateObjectsUsingBlock:^(WKBackForwardListItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
     if ([urlString isEqualToString:obj.URL.absoluteString]) {
     [self.webView goToBackForwardListItem:obj];
     hasBackRecord = YES;
     *stop = YES;
     }
     }];
     
     [self.webView.backForwardList.forwardList enumerateObjectsUsingBlock:^(WKBackForwardListItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
     if ([urlString isEqualToString:obj.URL.absoluteString]) {
     [self.webView goToBackForwardListItem:obj];
     hasBackRecord = YES;
     *stop = YES;
     }
     }];
     
     if (!hasBackRecord) {
     
     }
     */
    NSString *urlString = [NSString stringWithFormat:@"%@%@",self.linkURL,url];
    if (urlString && [urlString isKindOfClass:[NSString class]] && url.length > 0) [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]];
}

#pragma mark - 无纸化协议
- (void)nopaperView {
    CGRect appbounds = CGRectMake(0, CGRectGetHeight(self.view.bounds) - 55, [UIScreen mainScreen].bounds.size.width, 55);
    
    UIView* mainView = [[UIView alloc] initWithFrame:appbounds];
    mainView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:mainView];
    
    [mainView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.height.mas_equalTo(55);
    }];
    
    [self.webView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(-55);
    }];
    
    UIButton* agree = [UIButton buttonWithType:UIButtonTypeCustom];
    agree.frame = CGRectMake(15, mainView.bounds.origin.y, (mainView.bounds.size.width - 70) / 2, 40);
    [agree setTitle:@"不同意" forState:UIControlStateNormal];
    [agree setTitleColor:kColor_W forState:UIControlStateNormal];
    [agree.titleLabel setFont:[UIFont systemFontOfSize:13]];
    agree.backgroundColor = kColor_T;
    agree.layer.cornerRadius = 4;
    [agree addTarget:self action:@selector(agree:) forControlEvents:UIControlEventTouchUpInside];
    [mainView addSubview:agree];
    
    UIButton* notAgree = [UIButton buttonWithType:UIButtonTypeCustom];
    notAgree.frame = CGRectMake((mainView.bounds.size.width - 70) / 2 + 55, mainView.bounds.origin.y, (mainView.bounds.size.width - 70) / 2, 40);
    [notAgree setTitle:@"同意" forState:UIControlStateNormal];
    [notAgree setTitleColor:kColor_W forState:UIControlStateNormal];
    [notAgree.titleLabel setFont:[UIFont systemFontOfSize:13]];
    notAgree.backgroundColor = kColor_T;
    notAgree.layer.cornerRadius = 4;
    [notAgree addTarget:self action:@selector(notAgree:) forControlEvents:UIControlEventTouchUpInside];
    [mainView addSubview:notAgree];
}

- (void)agree:(UIButton*)sender {
    if (self.completed) self.completed(@"2", [NSURL URLWithString:@"uhomeoc://getNoPaperContent"]);
    //本小区已配置协议，用户接受协议，2同意，1不同意，0还没有设置
    [self segPopVC];
}

- (void)notAgree:(UIButton*)sender {
    if (self.completed) self.completed(@"1", [NSURL URLWithString:@"uhomeoc://getNoPaperContent"]);
    //本小区已配置协议，用户没有接受协议，2同意，1不同意，0还没有设置
    [self segPopVC];
}
#pragma mark - getter
-(SEGNaviHeaderView *)headerView{
    if (!_headerView) {
        _headerView = [[SEGNaviHeaderView alloc]init];
        _headerView.tag = self.headerViewTag;
        _headerView.delegate = self;
        _headerView.headerScrollView.delegate = self;
        _headerView.canShowCloseButton = YES;
        [_headerView.shareBtn setImage:[UIImage segBundleImageNamed:@"toolbar_btn_share"] forState:UIControlStateNormal];
    }
    return _headerView;
}

-(NSInteger)headerViewTag{
    if (!_headerViewTag) {
        _headerViewTag = 1005954;
    }
    return _headerViewTag;
}

-(SEGNaviHeaderView *)naviHideHeaderView{
    if (!_naviHideHeaderView) {
        _naviHideHeaderView = [[SEGNaviHeaderView alloc]initWithFrame:CGRectMake(0, LYStatusBarHeight(), [UIScreen mainScreen].bounds.size.width, kNavigationBarHeight)];
        _naviHideHeaderView.delegate = self;
        _naviHideHeaderView.headerScrollView.delegate = self;
        _naviHideHeaderView.backgroundColor = [UIColor clearColor];
        _naviHideHeaderView.hidden = YES;
    }
    return _naviHideHeaderView;
}

//-(NSURL *)currentUrl{
//    if (!_currentUrl) {
//        _currentUrl = [NSURL URLWithString: self.linkURL ? self.linkURL : @""];
//    }
//    return _currentUrl;
//}

- (UIView *)statusBarBackView {
    if (!_statusBarBackView) {
        _statusBarBackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), LYStatusBarHeight())];
        [self.view addSubview:_statusBarBackView];
    }
    [self.view bringSubviewToFront:_statusBarBackView];
    return _statusBarBackView;
}

-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
